package com.sneakxy.mybase4j.util;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

/**
 * @author 潜行的青衣
 * @see
 */
public class BeanHelper {

	public static interface TrimPloy {
		
		public String trim(String value);
		
	}
	
	public static void trim(Object obj, TrimPloy ploy) {
		Class<?> clazz = obj.getClass();
		List<Field> fields = FieldUtils.getAllFieldsList(clazz);
		Iterator<Field> it = fields.iterator();
		Field field = null;
		String value = null;
		boolean isAccessible = false;
		while(it.hasNext()) {
			field = it.next();
			if(field.getType() == String.class) {
				isAccessible = field.isAccessible();
				field.setAccessible(true);
				try {
					value = (String) field.get(obj);
					field.set(obj, ploy.trim(value));
				} catch (IllegalAccessException e) {
				}
				field.setAccessible(isAccessible);
			}
		}
	}
	
	public static void trim(Object obj) {
		trim(obj, new TrimPloy() {
			
			@Override
			public String trim(String value) {
				return StringUtils.trim(value);
			}
			
		});
	}
	
	public static void trimToEmpty(Object obj) {
		trim(obj, new TrimPloy() {
			
			@Override
			public String trim(String value) {
				return StringUtils.trimToEmpty(value);
			}
			
		});
	}
	
	public static void trimToNull(Object obj) {
		trim(obj, new TrimPloy() {
			
			@Override
			public String trim(String value) {
				return StringUtils.trimToNull(value);
			}
			
		});
	}
	
}
